/**
 * 读取一个目录中所有子目录和文件
 */
const fs = require('fs')
const path = require('path')

class File {
    constructor(filename, name, ext, isFile, size, creeateTime, updateTime) {
        this.filename = filename
        this.name = name // 文件名
        this.ext = ext // 后缀
        this.isFile = isFile // 是否文件
        this.size = size // 文件大小
        this.creeateTime = creeateTime // 创建时间
        this.updateTime = updateTime // 更新时间
    }

    static async getFile(filename) {
        const stat = await fs.promises.stat(filename)
        const { size, birthtime, mtime } = stat
        let name = path.basename(filename),
            ext = path.extname(filename),
            isFile = stat.isFile(),
            creeateTime = new Date(birthtime),
            updateTime = new Date(mtime);
        return new File(filename, name, ext, isFile, size, creeateTime, updateTime)
    }

    // 获取目录的所有子文件对象，如果是文件返回空数组
    async getChildren() {
        if (this.isFile) { return [] }
        let dirArr = await fs.promises.readdir(this.filename);
        dirArr = dirArr.map(fileName => {
            const filename = path.resolve(this.filename, fileName)
            return File.getFile(filename)
        })
        return Promise.all(dirArr)
    }

    // 获取文件内容， 如果是目录，返回null
    async getContent(isBuffer = false) {
        if (!this.isFile) { return null }
        if (isBuffer) {
            return await fs.promises.readFile(this.filename)
        }
        return await fs.promises.readFile(this.filename, 'utf-8')
    }
}

async function readDir(dirname) {
    const file = await File.getFile(dirname)
    return await file.getChildren()
}

const dirname = path.resolve(__dirname, '../file')
console.log(readDir(dirname))

async function test() {
    const dirname = path.resolve(__dirname, '../file')
    const filename = path.resolve(__dirname, './index.js')

    const dir = await File.getFile(dirname)
    console.log('dir', await dir.getChildren())

    const file = await File.getFile(filename)
    console.log('file', file)

}
// test()
